//
//  TPViewController.m
//  nobalmetal
//
//  Created by Carlson Lee on 2017/3/14.
//  Copyright © 2017年 judu. All rights reserved.
//

#import "TPViewController.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import <objc/runtime.h>
#import "Masonry.h"
#import <WebKit/WebKit.h>
//#import "XNAliyun.h"
#import "CardScrollView.h"
#import "LayoutView.h"
#import "OutLabel.h"

@interface TPViewController ()<UIImagePickerControllerDelegate, UINavigationControllerDelegate, WKUIDelegate,WKNavigationDelegate, UITextViewDelegate, NSStreamDelegate, UICollectionViewDelegate, UICollectionViewDataSource>
{
    CATextLayer *textLayer;
    UILabel* textLab;
    CAGradientLayer *gradientLayer;
    UIView* bgView;
    WKWebView* _webView;
    
    NSThread *A;
    NSMutableData* data;
}
@property(nonatomic, strong)NSString* user;
@property(nonatomic, strong)UILabel* textLab;
@property (nonatomic, strong)UITextView *textView;
@property(nonatomic, strong)CardScrollView* cardView;
@property(nonatomic, strong)CAShapeLayer* mask;//遮罩
@end

NSString* const t_time = @"3.1415926";
const NSString* tt_time = @"asdf";

NSString* const CELL_ID = @"cell_id";
@implementation TPViewController

- (NSString *)user
{
    return _user;
}

- (CardScrollView *)cardView
{
    if(!_cardView){
        _cardView = [[CardScrollView alloc]init];
        [self.view addSubview:_cardView];
    }
    return _cardView;
}

- (CAShapeLayer *)mask
{
    if(!_mask){
        _mask = [CAShapeLayer layer];
        [_mask setFillColor:[UIColor blackColor].CGColor];
        [_mask setBackgroundColor:[UIColor clearColor].CGColor];
    }
    return _mask;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self setUp];
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (UILabel *)textLab
{
    if(!_textLab){
        _textLab = [[UILabel alloc]init];
        [self.view addSubview:_textLab];
        
        [_textLab setFont:[UIFont systemFontOfSize:20]];
        [_textLab setTextColor:[UIColor blackColor]];
        _textLab.text = @"习惯不曾习惯的习惯会习惯 舍得不曾舍得的舍得会舍得";
//        [_textLab setBackgroundColor:[UIColor redColor]];
    }
    return _textLab;
}

#pragma mark------------------privateMethod


- (void)setUp
{
    /*
    UIButton* btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setTitle:@"点 击" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    btn.frame = CGRectMake((mainWidth-100)/2, (mainHeight-100)/2, 100, 100);
    [self.view addSubview:btn];
    [btn addTarget:self action:@selector(showVideo) forControlEvents:UIControlEventTouchUpInside];
    */

//    _webView = [[WKWebView alloc]initWithFrame:self.view.bounds];
//    [self.view addSubview:_webView];
//    _webView.UIDelegate = self;
//    _webView.navigationDelegate = self;
//    [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://testwww.xnsudai.com/html/page/guanjia_invite.html"]]];
    
    UITextView *textView  = [[UITextView alloc] initWithFrame:CGRectMake(20, 100, self.view.bounds.size.width - 20, 100)];
    textView.delegate = self;
    textView.editable = NO;
    textView.scrollEnabled = NO;
    
    self.textView = textView;
    NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:@"客服电话：400-775-5333 转4 (每天9:00-20:00)"];
    [attr setAttributes:@{NSForegroundColorAttributeName:[UIColor blackColor],NSFontAttributeName:[UIFont systemFontOfSize:14]} range:NSMakeRange(0, attr.length)];
    //点击了链接拨打电话
    [attr setAttributes:@{NSForegroundColorAttributeName:[UIColor colorWithRed:0 green:147/255.0 blue:238/255.0 alpha:1],
                          NSFontAttributeName:[UIFont systemFontOfSize:14],
                          NSLinkAttributeName:@"telprompt://400-775-5333"}
     //如果点击了之后跳转网页可以将NSLinkAttributeName后面的修改为想要跳转的网页
                  range:NSMakeRange(5, 15)];
    textView.attributedText = attr;
    [self.view addSubview:textView];
    
//    [[XNAliyun sharedInstance] setupEnvironment];
//    UIButton* btn = [UIButton buttonWithType:UIButtonTypeCustom];
//    [self.view addSubview:btn];
//    btn.frame = CGRectMake(100, 100, 100, 100);
//    [btn setTitle:@"上传" forState:UIControlStateNormal];
//    [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//    [btn addTarget:self action:@selector(upload) forControlEvents:UIControlEventTouchUpInside];
    
    
//    CGFloat f_w = mainWidth/2;
//    self.cardView.frame = CGRectMake((mainWidth-f_w)/2, 200, f_w, 100);
//    self.cardView.objs = @[@"", @"", @""];
    
    /*
    LayoutView* layout = [[LayoutView alloc]init];
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    UICollectionView* collection = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 200, mainWidth, 300) collectionViewLayout:layout];
    [self.view addSubview:collection];
    collection.pagingEnabled = YES;
    collection.delegate = self;
    collection.dataSource = self;
    [collection registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:CELL_ID];
     */
    
    
//    [self bitmap];
    
//    [self bitmap2];
    
    /*
    NSString* str = @"hello,财猫易贷是一个贷款平台，涵盖多种贷款产品，多大上百个口子";
    NSMutableParagraphStyle* style = [[NSMutableParagraphStyle alloc]init];
//    style.firstLineHeadIndent = 50;
    style.headIndent = 0.0f;
    style.lineSpacing = 10.0f;
    style.lineBreakMode = NSLineBreakByWordWrapping;
    NSAttributedString* attribute = [[NSAttributedString alloc]initWithString:str attributes:@{NSParagraphStyleAttributeName:style, NSKernAttributeName:@(0)}];
    CGSize sz = [str boundingRectWithSize:CGSizeMake(80, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSParagraphStyleAttributeName:style, NSFontAttributeName:[UIFont systemFontOfSize:16]} context:nil].size;
    NSLog(@"===%@", NSStringFromCGSize(sz));
    
    CGRect rt = CGRectMake(50, 200, sz.width, sz.height);
    UILabel* lab = [[UILabel alloc]initWithFrame:rt];
    [self.view addSubview:lab];
    [lab setBackgroundColor:[UIColor redColor]];
    lab.numberOfLines = 0;
//    lab.text = str;
    lab.attributedText = attribute;
    [lab setTextColor:UIColorFromRGB(0x000000)];
    [lab setFont:[UIFont systemFontOfSize:16]];
    */
    
    
}

- (void)bitmap2
{
    UIGraphicsBeginImageContext(CGSizeMake(10, 10));
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, UIColorFromRGB(0xff0000).CGColor);
    CGContextAddRect(context, CGRectMake(0, 0, 10, 10));
    CGContextFillPath(context);
    unsigned char* data = CGBitmapContextGetData(context);
    UIGraphicsEndImageContext();
    
    for(int i=0; i<10; i++){
        for(int j=0; j<40; j+=4){
            int n = i*10+j;
            NSLog(@"%c", data[n]);
        }
        NSLog(@"%@", @"\n");
    }
}

#define Mask8(x) ( (x) & 0xFF )
#define R(x) ( Mask8(x) )
#define G(x) ( Mask8(x >> 8 ) )
#define B(x) ( Mask8(x >> 16) )

- (void)bitmap
{
    UIImage* img = [UIImage imageNamed:@"gj_icon"];

    CGImageRef imgRef = CGImageCreateWithImageInRect(img.CGImage, CGRectMake(10, 10, 5, 5));
    NSUInteger width = CGImageGetWidth(imgRef);
    NSUInteger height = CGImageGetHeight(imgRef);
    NSUInteger bitsPerComponent = 8;
    NSUInteger bytesPerPixel = 4;
    NSUInteger bytesPerRow = width * bytesPerPixel;
    CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();
    
    UInt32* pixels;
    pixels = calloc(width*height, bytesPerPixel);
    
    CGContextRef context = CGBitmapContextCreate(pixels, width, height, bitsPerComponent, bytesPerRow, space, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
    CGContextDrawImage(context, CGRectMake(0, 0, width, height), imgRef);
    
    CGColorSpaceRelease(space);
    CGContextRelease(context);
    
    for(int i=0; i<height; i++){
        for(int j=0; j<width; j++){
            UInt32 color = * pixels;
            printf("%d-%d-%d ",   R(color),G(color),B(color));
            pixels++;
        }
        printf("\n");
    }
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 20;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell* cell = [collectionView dequeueReusableCellWithReuseIdentifier:CELL_ID forIndexPath:indexPath];
    [cell setBackgroundColor:UIColorFromRGB(0xf00000)];
    
    return cell;
}

- (void)upload
{
//    [[XNAliyun sharedInstance] uploadObject:[UIImage imageNamed:@"gj_icon"]];
    
    NSInputStream* input = [NSInputStream inputStreamWithData:UIImagePNGRepresentation([UIImage imageNamed:@"gj_icon"])];
    input.delegate = self;
    [input scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [input open];
    
    NSURL* url = [NSURL URLWithString:@"https://testcredit.xnsudai.com/card/pinganyinhangmax@2x.png"];
    
    
}

- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode
{
    switch (eventCode) {
        case NSStreamEventHasBytesAvailable:{
            if(!data){
                data = [NSMutableData data];
            }
            uint8_t buf[1024];
            unsigned int len = 0;
            len = [(NSInputStream*)aStream read:buf maxLength:1024];
            if(len){
                [data appendBytes:(const void*)buf length:len];
            }
            NSLog(@"=====%d", len);
        }
            break;
        case NSStreamEventEndEncountered:{
            [aStream close];
            [aStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
        }
            break;
        default:
            break;
    }
}

- (void)test
{
    NSLog(@"----------------");
//    NSTimer* timer = [NSTimer scheduledTimerWithTimeInterval:2.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
//        NSLog(@"------=======timer");
//    }];
    [[NSRunLoop currentRunLoop]addPort:[NSPort port] forMode:NSDefaultRunLoopMode];
    
    [NSThread detachNewThreadSelector:@selector(runB) toTarget:self withObject:nil];

    while (YES) {
        if([[NSRunLoop currentRunLoop]runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]){
            NSLog(@"线程B结束");
            break;
        }
    }
    NSLog(@"==%@", [NSRunLoop currentRunLoop]);
}

- (void)runB
{
    sleep(5);
    [self performSelector:@selector(run) onThread:A withObject:nil waitUntilDone:YES modes:@[NSDefaultRunLoopMode]];
}

- (void)run
{
    
}

-(BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange{
    return YES;
}


// 在收到响应后，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
    
    NSLog(@"=%@",navigationResponse.response.URL.absoluteString);
    //允许跳转
    decisionHandler(WKNavigationResponsePolicyAllow);
    //不允许跳转
    //decisionHandler(WKNavigationResponsePolicyCancel);
}
// 在发送请求之前，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    
    NSLog(@"-%@",navigationAction.request.URL.absoluteString);
    //允许跳转
    decisionHandler(WKNavigationActionPolicyAllow);
    //不允许跳转
    //decisionHandler(WKNavigationActionPolicyCancel);
}

- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler
{
    if([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]){
        NSURLCredential* card = [[NSURLCredential alloc]initWithTrust:challenge.protectionSpace.serverTrust];
        completionHandler(NSURLSessionAuthChallengeUseCredential, card);
    }
}

- (void)showVideo
{
    /*
    UIImagePickerController *camera = [UIImagePickerController new];
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
        NSArray *availableMediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
        if([availableMediaTypes containsObject:(NSString *)kUTTypeMovie]){
            camera.sourceType = UIImagePickerControllerSourceTypeCamera;
            camera.mediaTypes = @[(NSString *)kUTTypeMovie];
            camera.delegate = self;
            [self presentViewController:camera animated:YES completion:^{
                
            }];
        }
        
    }
     */
    
    
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
